import express from 'express';
import mqtt from 'mqtt';

const router = express.Router();
const mqttClient = mqtt.connect('mqtt://localhost');

// 路径存储与转发
router.post('/routes', async (req, res) => {
  const { deviceId, path } = req.body;
  
  try {
    // 存储到数据库
    await db.query(
      `INSERT INTO routes (device_id, path) 
       VALUES ($1, $2)`,
      [deviceId, JSON.stringify(path)]
    );

    // MQTT消息发布
    mqttClient.publish(
      `cars/${deviceId}/route`,
      JSON.stringify({
        type: 'route',
        path: path.map(p => [p.lng, p.lat])
      }),
      { qos: 1 }
    );

    res.json({ success: true });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// WebSocket服务
router.ws('/ws/:deviceId', (ws, req) => {
  const deviceId = req.params.deviceId;
  
  // MQTT订阅实时位置
  const positionHandler = (topic, message) => {
    ws.send(message.toString());
  };
  
  mqttClient.subscribe(`cars/${deviceId}/position`);
  mqttClient.on('message', positionHandler);

  ws.on('close', () => {
    mqttClient.unsubscribe(`cars/${deviceId}/position`);
    mqttClient.removeListener('message', positionHandler);
  });
});

export default router;